<?php
  class glbpay {
    /**
	 * representing the payment method
	 */
	var $code;
	/**
	 * the displayed name for this payment method
	 */
	var $title;
	/**
	 * a soft name for this payment method
	 */
	var $description;
	/**
	 * $enabled determines whether this module shows or not
	 */
	var $enabled;
	/**
	 * sort order of display
	 */
	var $sort_order;
	/**
	 * order status setting for completed orders
	 */
	var $order_status;
	
	function _log($msg,$lavel)
	{
		error_log(date('Y-m-d H:i:s',time())." ".$lavel." - ".$msg . ";\r\n", 3, DIR_FS_SQL_CACHE."/glbpay-info-".date('Y-m-d',time()).".log");
	}
	/**
	 * constructor function
	 */
	function glbpay()
	{
		global $order, $messageStack;
		$this->code="glbpay";
		$this->title=MODULE_PAYMENT_GLBPAY_TEXT_ADMIN_TITLE;
		$this->description=MODULE_PAYMENT_GLBPAY_TEXT_DESCRIPTION;
		$this->sort_order=MODULE_PAYMENT_GLBPAY_SORT_ORDER;
        $this->enabled = ((MODULE_PAYMENT_GLBPAY_STATUS == 'True') ? true : false);
        if ((int)MODULE_PAYMENT_GLBPAY_ORDER_STATUS_ID > 0)
        {
            $this->order_status = MODULE_PAYMENT_GLBPAY_ORDER_STATUS_ID;
        }
        if(is_object($order))
        {
        	$this->update_status();
        }
		$this->form_action_url=zen_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL', false); 
	}

	/**
	 *calculate zone matches and flag settings to determine whether this module should display to customers or not
	 */
	function update_status()
	{
		global $db,$order;
		if(($this->enabled==true)&&((int)MODULE_PAYMENT_GLBPAY_ZONE > 0))
		{
			$check_flag=false;
			$check_query=$db->Execute("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_GLBPAY_ZONE . "' and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id");
			while(!$check_query->EOF)
			{
				if($check_query->fields['zone_id'] < 1)
				{
					$check_flag=true;
					break;
				}
				elseif($check_query->fields['zone_id'] == $order->billing['zone_id'])
				{
					$check_flag=true;
					break;
				}
				$check_query->MoveNext();
			}
			if($check_flag==false)
			{
				$this->enabled=false;
			}
		}
	}

	/**
	 * JS validation which does error-checking of data-entry if this module is selected for use
	 */
	// Validate the credit card information via javascript (Number, Owner, and CVV Lengths)
  function javascript_validation() {
    $js = '  if (payment_value == "' . $this->code . '") {' . "\n" .
          '    var cc_firstname = document.checkout_payment.glbpay_api_cc_firstname.value;' . "\n" .
		  '    var cc_lastname = document.checkout_payment.glbpay_api_cc_lastname.value;' . "\n" .
          '    var cc_number = document.checkout_payment.glbpay_api_cc_number.value;' . "\n" .
          '    var cc_cvv = document.checkout_payment.glbpay_api_cc_cvv.value;' . "\n" .
		  '    var cc_inssuebank = document.checkout_payment.glbpay_api_cc_inssue_bank.value;' . "\n" .
          '    if (cc_firstname == "" || cc_firstname.length < ' . CC_OWNER_MIN_LENGTH . ') {' . "\n" .
          '      error_message = error_message + "' . MODULE_PAYMENT_GLBPAY_API_TEXT_JS_CC_FIRSTNAME . '";' . "\n" .
          '      error = 1;' . "\n" .
          '    }' . "\n" .
		   '   if (cc_lastname == "" || cc_lastname.length < ' . CC_OWNER_MIN_LENGTH . ') {' . "\n" .
          '      error_message = error_message + "' . MODULE_PAYMENT_GLBPAY_API_TEXT_JS_CC_LASTNAME . '";' . "\n" .
          '      error = 1;' . "\n" .
          '    }' . "\n" .
          '    if (cc_number == "" || cc_number.length < ' . CC_NUMBER_MIN_LENGTH . ') {' . "\n" .
          '      error_message = error_message + "' . MODULE_PAYMENT_GLBPAY_API_TEXT_JS_CC_NUMBER . '";' . "\n" .
          '      error = 1;' . "\n" .
          '    }' . "\n" .
          '    if (cc_cvv == "" || cc_cvv.length < "3") {' . "\n".
          '      error_message = error_message + "' . MODULE_PAYMENT_GLBPAY_API_TEXT_JS_CC_CVV . '";' . "\n" .
          '      error = 1;' . "\n" .
          '    }' . "\n" .
		   '   if (cc_inssuebank == "" || cc_inssuebank.length < "2") {' . "\n".
          '       error_message = error_message + "' . MODULE_PAYMENT_GLBPAY_API_TEXT_JS_CC_INSSUE_BANK . '";' . "\n" .
          '       error = 1;' . "\n" .
          '    }' . "\n" .
          '  }' . "\n";

    return $js;
  }

  // Display Credit Card Information Submission Fields on the Checkout Payment Page
  function selection() {   
    global $order;

    for ($i=1; $i<13; $i++) {
      $expires_month[] = array('id' => sprintf('%02d', $i), 'text' => strftime('%B - (%m)',mktime(0,0,0,$i,1,2000)));
    }

    $today = getdate();
    for ($i=$today['year']; $i < $today['year']+15; $i++) {
      $expires_year[] = array('id' => strftime('%Y',mktime(0,0,0,1,1,$i)), 'text' => strftime('%Y',mktime(0,0,0,1,1,$i)));
    }

    $onFocus = ' onfocus="methodSelect(\'pmt-' . $this->code . '\')"';

    $selection = array('id' => $this->code,
                       'module' => $this->title,
                       'fields' => array(array('title' => MODULE_PAYMENT_GLBPAY_API_TEXT_CREDIT_CARD_FirstName,
                                               'field' => zen_draw_input_field('glbpay_api_cc_firstname', $order->billing['firstname'] , 'id="'.$this->code.'-cc-firstname"'. $onFocus . ' autocomplete="off"'),
                                                'tag' => $this->code.'-cc-firstname'),
										 array('title' => MODULE_PAYMENT_GLBPAY_API_TEXT_CREDIT_CARD_LastName,
                                               'field' => zen_draw_input_field('glbpay_api_cc_lastname', $order->billing['lastname'], 'id="'.$this->code.'-cc-lastname"'. $onFocus . ' autocomplete="off"'),
                                                'tag' => $this->code.'-cc-lastname'),
                                         array('title' => MODULE_PAYMENT_GLBPAY_API_TEXT_CREDIT_CARD_NUMBER,
                                               'field' => zen_draw_input_field('glbpay_api_cc_number', $ccnum, 'id="'.$this->code.'-cc-number"' . $onFocus . ' autocomplete="off"'),
                                                 'tag' => $this->code.'-cc-number'),
                                         array('title' => MODULE_PAYMENT_GLBPAY_API_TEXT_CREDIT_CARD_EXPIRES,
                                               'field' => zen_draw_pull_down_menu('glbpay_api_cc_expires_month', $expires_month, strftime('%m'), 'id="'.$this->code.'-cc-expires-month"' . $onFocus) . '&nbsp;' . zen_draw_pull_down_menu('glbpay_api_cc_expires_year', $expires_year, '', 'id="'.$this->code.'-cc-expires-year"' . $onFocus),
                                                 'tag' => $this->code.'-cc-expires-month'),
                                         array('title' => MODULE_PAYMENT_GLBPAY_API_TEXT_CVV,
                                               'field' => zen_draw_input_field('glbpay_api_cc_cvv', '', 'size="4" maxlength="4"'. ' id="'.$this->code.'-cc-cvv"' . $onFocus . ' autocomplete="off"') . ' ' . '<a href="javascript:popupWindow(\'' . zen_href_link(FILENAME_POPUP_CVV_HELP) . '\')">' . MODULE_PAYMENT_GLBPAY_API_TEXT_POPUP_CVV_LINK . '</a>',
                                                 'tag' => $this->code.'-cc-cvv'),
										array('title' => MODULE_PAYMENT_GLBPAY_API_TEXT_INSSUE_BANK,
                                               'field' => zen_draw_input_field('glbpay_api_cc_inssue_bank', '', 'size="20" maxlength="50"'. ' id="'.$this->code.'-cc-inssue-bank"' . $onFocus . ' autocomplete="off"'),
                                                 'tag' => $this->code.'-cc-inssue-bank'))); 
	return $selection;
  }

	/**
	 * evaluates the Credit Card Type for acceptance and the validity of the Credit Card Number & Expiration Date
	 * glbpay module is not collecting info, it simply skips this step.
	 */
	// Evaluates the Credit Card Type for acceptance and the validity of the Credit Card Number & Expiration Date
  function pre_confirmation_check() { 
    global $db, $messageStack;

    include(DIR_WS_CLASSES . 'cc_validation.php');

    $cc_validation = new cc_validation();
    $result = $cc_validation->validate($_POST['glbpay_api_cc_number'], $_POST['glbpay_api_cc_expires_month'], $_POST['glbpay_api_cc_expires_year']);
    $error = '';
    switch ($result) {
      case -1:
        $error = sprintf(TEXT_CCVAL_ERROR_UNKNOWN_CARD, substr($cc_validation->cc_number, 0, 4));
        break;
      case -2:
      case -3:
      case -4:
        $error = TEXT_CCVAL_ERROR_INVALID_DATE;
        break;
      case false:
        $error = TEXT_CCVAL_ERROR_INVALID_NUMBER;
        break;
    }

    // save record of errors which occur during checkout_payment validation phase but haven't been sent to gateway yet
    if ( ($result == false) || ($result < 1) ) {
      $payment_error_return = 'payment_error=' . $this->code ;
      $error_info2 = '&error=' . urlencode($error) . '&glbpay_api_cc_firstname=' . urlencode($_POST['glbpay_api_cc_firstname']). '&glbpay_api_cc_lastname=' . urlencode($_POST['glbpay_api_cc_lastname'])  . '&glbpay_api_cc_expires_month=' . $_POST['glbpay_api_cc_expires_month'] . '&glbpay_api_cc_expires_year=' . $_POST['glbpay_api_cc_expires_year'].'&glbpay_api_cc_inssue_bank'.$_POST["glbpay_api_cc_expires_year"];
      $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->', 'error');
      zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
    }

    // if no error, continue with validated data:
    $this->cc_card_type = $cc_validation->cc_type;
    $this->cc_card_number = $cc_validation->cc_number;
    $this->cc_expiry_month = $cc_validation->cc_expiry_month;
    $this->cc_expiry_year = $cc_validation->cc_expiry_year; 
  }

	/**
	 * Display Credit Card Information on the Checkout Confirmation Page
	 * Since none is collected for glbpay before forwarding to glbpay site, this is skipped
	 */
	function confirmation($flag = '')
	{		 
		 $confirmation = array('title' => $this->title . ': ' . $this->cc_card_type,
                          'fields' => array(array('title' => MODULE_PAYMENT_GLBPAY_API_TEXT_CREDIT_CARD_FirstName,
                                                  'field' => $_POST['glbpay_api_cc_firstname']),
											array('title' => MODULE_PAYMENT_GLBPAY_API_TEXT_CREDIT_CARD_LastName,
                                                  'field' => $_POST['glbpay_api_cc_lastname']),
                                            array('title' => MODULE_PAYMENT_GLBPAY_API_TEXT_CREDIT_CARD_NUMBER,
                                                  'field' => str_repeat('X', (strlen($this->cc_card_number) - 4)) . substr($this->cc_card_number, -4)),
                                            array('title' => MODULE_PAYMENT_GLBPAY_API_TEXT_CREDIT_CARD_EXPIRES,
                                                  'field' => strftime('%B, %Y', mktime(0,0,0,$this->cc_expiry_month, 1, $this->cc_expiry_year))),
											array('title' => MODULE_PAYMENT_GLBPAY_API_TEXT_INSSUE_BANK,
                                                  'field' => $_POST['glbpay_api_cc_inssue_bank'])	  
												  )); 
		return $confirmation;
	}

	/**
	 * creat order before payment
	 */
	private function create_order()
	{
		global $order, $order_totals;
		$order->info['payment_method'] = 'Credit card online payment';
		$order->info['payment_module_code'] = $this->code;
		$order->info['order_status'] = MODULE_PAYMENT_GLBPAY_PROCESSING_STATUS_ID;
		$glbpay_order_id = $order->create($order_totals, 2);
		$order->create_add_products($glbpay_order_id);
		return $glbpay_order_id;
	}
	
	private function delete_order($order_id)
	{
	
	}

	function process_button()
	{
		global $order;		  	
		$process_button_string = zen_draw_hidden_field('cc_firstname', $_POST['glbpay_api_cc_firstname']) .
							 zen_draw_hidden_field('cc_lastname', $_POST['glbpay_api_cc_lastname']) .
                             zen_draw_hidden_field('cc_expires', $this->cc_expiry_month . $this->cc_expiry_year).
                             zen_draw_hidden_field('cc_expires_month', $this->cc_expiry_month) .
                             zen_draw_hidden_field('cc_expires_year', $this->cc_expiry_year).
                             zen_draw_hidden_field('cc_type', $this->cc_card_type) .
                             zen_draw_hidden_field('cc_number', $this->cc_card_number) .
                             zen_draw_hidden_field('cc_cvv', $_POST['glbpay_api_cc_cvv']).
							 zen_draw_hidden_field('cc_inssue_bank', $_POST['glbpay_api_cc_inssue_bank']).
							 zen_draw_hidden_field('cc_deliveryname', $order->billing['firstname'].' '.$order->billing['lastname']);
		$process_button_string .= zen_draw_hidden_field(zen_session_name(), zen_session_id()); 
		return $process_button_string;
	}

	function before_process()
	{
		require('includes/modules/payment/glbpay/glbpay_payresult.php'); 
		global $order, $order_totals, $db, $messageStack, $lp_avs, $lp_trans_num,$currencies;
		$m_order=array();
		$m_order["Cmd"]="paymentbackend";
		$m_order["version"]="1.1.0";
		$m_order["language"]="en-us";
		$m_order["merchantid"]=MODULE_PAYMENT_GLBPAY_MERCHANTID;
		
		//creat orderid
		$new_order_id=$this->create_order();
		$m_order["orderid"]=MODULE_PAYMENT_GLBPAY_ORDER_PREFIX .str_pad($new_order_id, 10, '0', STR_PAD_LEFT);		
		//orderdate: null date or 19700101  
		if(empty($order->info['date_purchased']))
        {
        	$m_order["orderdate"]=date('YmdHis');
        } 
        else
        {
        	$m_order["orderdate"]=date('YmdHis',strtotime($order->info['date_purchased']));
        }
		$m_order["currency"]=$order->info['currency'];
		$m_order["orderamount"] = sprintf('%.2f', $order->info['total']* $currencies->get_value($m_order["currency"]));
        $m_order["callbackurl"]=str_replace(".php.html",".php",zen_href_link('glbpay_checkout.php', 'referer=glbpay', 'SSL',false,false,true));
		$m_order["browserbackurl"]=str_replace(".php.html",".php",zen_href_link('glbpay_checkout.php', 'referer=glbpay', 'SSL',false,false,true));
		$m_order["remark1"]='';
		$m_order["remark2"]=$this->replaceCharacter($new_order_id);
		$m_order["remark3"]='';
		
		//product info
		$strProduct = array();
        $strProductdes='';
        $i=0;
        for (; $i<sizeof($order->products)&&$i<50; $i++) {
        	  $tempsn=$this->strcheck($order->products[$i]["id"]);
        	  $tempprice=sprintf('%.2f', $order->products[$i]["price"]* $currencies->get_value($currency));
        	  $tempname=trim($order->products[$i]["name"]);
        	  $strProductdes=$strProductdes.html_entity_decode($tempname,ENT_NOQUOTES,"UTF-8").$tempsn.$order->products[$i]["qty"].$tempprice;
              $product=array('ProductName'=>$tempname,'ProductSn'=>$tempsn,'Quantity'=>$order->products[$i]["qty"],'Unit'=>$tempprice);
			  array_push($strProduct,$product); 			  
        }
		$m_order["Products"]=$strProduct;
		//billing info
		$m_order["billaddress"]=$this->replaceCharacter($order->billing['street_address']); 
		$m_order["billcountry"]=$this->replaceCharacter($order->billing['country']['iso_code_3']);
		$m_order["billprovince"]=$this->replaceCharacter($order->billing['state']); 
		$m_order["billcity"]=$this->replaceCharacter($order->billing['city']);
		$m_order["billemail"]= $this->replaceCharacter($order->customer['email_address']);
		$m_order["billphone"]=$this->replaceCharacter($order->customer['telephone']);
		$m_order["billpost"]=$this->replaceCharacter($order->billing['postcode']);
		
		//shipping info 
		$m_order["deliveryname"]= $this->replaceCharacter($_POST['cc_deliveryname']); 
		$m_order["deliveryaddress"]= $this->replaceCharacter($order->delivery['street_address']); 
		$m_order["deliverycountry"]=$this->replaceCharacter($order->delivery['country']['iso_code_3']);
		$m_order["deliveryprovince"]=$this->replaceCharacter($order->delivery['state']); 
		$m_order["deliverycity"]= $this->replaceCharacter($order->delivery['city']);
		$m_order["deliveryemail"]=$this->replaceCharacter($order->customer['email_address']);
		$m_order["deliveryphone"]=$this->replaceCharacter($order->customer['telephone']);
		$m_order["deliverypost"]=$this->replaceCharacter($order->delivery['postcode']);
		
		//card info
		$m_order["cardnumber"]=$_POST['cc_number'];
		//card type
		$firstnum=substr($m_order["cardnumber"],0,1);
		if($firstnum=='4'){
			$m_order["cardtype"]='1';
		}elseif($firstnum=='5'){
			$m_order["cardtype"]='2';
		}elseif($firstnum=='3'){
			$m_order["cardtype"]='3';
		}		
		$m_order["Cvv"]=$_POST['cc_cvv'];
		$m_order["ExpYear"]=$_POST['cc_expires_year'];
		$m_order["ExpMonth"]= $_POST['cc_expires_month']; 
		//$m_order["CardFirstName"]=$_POST['cc_owner'];
		$m_order["CardFirstName"]=$_POST['cc_firstname'];
		$m_order["CardLastName"]=$_POST['cc_lastname'];
		$m_order["IssueBank"]=$_POST['cc_inssue_bank'];
		$m_order["Clientip"]=$this->getIp();
		$m_order["ShopType"]='zencart';
		$m_order["accessUrl"]=$_SERVER['SERVER_NAME'];
		$signStr= $m_order["Cmd"].$m_order["version"].$m_order["merchantid"].$m_order["orderid"].$m_order["orderdate"].$m_order["currency"].$m_order["orderamount"]
				 .$m_order["accessUrl"].$m_order["callbackurl"].$m_order["ShopType"].$m_order["remark1"].$m_order["remark2"].$m_order["remark3"].$strProductdes
				 .$m_order["billaddress"].$m_order["billcountry"].$m_order["billprovince"].$m_order["billcity"].$m_order["billemail"].$m_order["billphone"]
				 .$m_order["billpost"].$m_order["deliveryname"].$m_order["deliveryaddress"].$m_order["deliverycountry"].$m_order["deliveryprovince"].$m_order["deliverycity"]
				 .$m_order["deliveryemail"].$m_order["deliveryphone"].$m_order["deliverypost"].$m_order["cardnumber"].$m_order["cardtype"].$m_order["Cvv"]
				 .$m_order["ExpYear"].$m_order["ExpMonth"].$m_order["CardFirstName"].$m_order["CardLastName"].$m_order["IssueBank"].$m_order["Clientip"]; 
		$m_order["signature"]=md5(MODULE_PAYMENT_GLBPAY_SSLKEY.$signStr);  
		// send request to gateway
		$payUrl='';
		if(MODULE_PAYMENT_GLBPAY_HANDLER == 'Live'){
			$payUrl='https://pgw.glbpay.com/Api/PaymentBackend'; 
		}else{
			$payUrl='http://api.grapay.net:87/Api/PaymentBackend';
		}
		$this->_log('begin call api, orderid:'.$order_id,'INFO');
		$result = @$this->GetWebContent($payUrl,json_encode($m_order));  
		$this->_log('api result :'.$result,'INFO');				
		$payResult=new payResult();
		//处理订单状态
		$payResult->UpdateOrder($result); 
		return true;
    }

	function after_process()
	{ 
	 	return false;
	 }
	/**
	 * Used to display error message details
	 */
	function output_error()
	{
		return false;
	}
	/**
	 * Check to see whether module is installed
	 */
	function check()
	{
		global $db;
		if(!isset($this->_check))
		{
			$check_query=$db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_GLBPAY_STATUS'");
			$this->_check=$check_query->RecordCount();
		}
		return $this->_check;
	}

	/**
	 * Install the payment module and its configuration settings
	 */
	function install(){
		global $db, $language, $module_type;
		$this->_log("install glbpay plugin","INFO");
		if (!defined('MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_1_1'))
		{
			 include(DIR_FS_CATALOG_LANGUAGES . $_SESSION['language'] . '/modules/' . $module_type . '/' . $this->code . '.php');
		}
	    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_1_1 . "', 'MODULE_PAYMENT_GLBPAY_STATUS', 'True', '" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_1_2 . "', '9', '1', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_2_1 . "', 'MODULE_PAYMENT_GLBPAY_MERCHANTID', '', '" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_2_2 . "', '9', '2', now())");
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_3_1 . "', 'MODULE_PAYMENT_GLBPAY_SSLKEY', '', '" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_3_2 . "', '9', '3', now())");
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_9_1 . "', 'MODULE_PAYMENT_GLBPAY_ORDER_PREFIX', '', '" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_9_2 . "', '9', '4', now())");
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_4_1 . "', 'MODULE_PAYMENT_GLBPAY_ZONE', '0', '" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_4_2 . "', '9', '5', 'zen_get_zone_class_title', 'zen_cfg_pull_down_zone_classes(', now())");
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_5_1 . "', 'MODULE_PAYMENT_GLBPAY_PROCESSING_STATUS_ID', '1', '" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_5_2 . "', '9', '6', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_6_1 . "', 'MODULE_PAYMENT_GLBPAY_ORDER_STATUS_ID', '2', '" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_6_2 . "', '9', '7', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_7_1 . "', 'MODULE_PAYMENT_GLBPAY_SORT_ORDER', '0', '" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_7_2 . "', '9', '8', now())");
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_8_1 . "', 'MODULE_PAYMENT_GLBPAY_HANDLER', 'Live', '" . MODULE_PAYMENT_GLBPAY_TEXT_CONFIG_8_2 . "', '9', '9', 'zen_cfg_select_option(array(\'Live\', \'Test\'), ', now())");

        $db->Execute("CREATE TABLE IF NOT EXISTS glbpay_session (
                      unique_id int(11) NOT NULL auto_increment,
                      session_id text NOT NULL,
                      orders_id text NOT NULL,
                      session_info blob NOT NULL,
                      session_date datetime NOT NULL default '0001-01-01 00:00:00',
                      PRIMARY KEY  (unique_id),
                      KEY idx_session_id_zen ( session_id(36) )
                      ) CHARACTER SET utf8 COLLATE utf8_general_ci;");
	}
	/**
	 * Remove the module and all its settings
	 */
	function remove(){
		global $db;
		$db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key LIKE  'MODULE_PAYMENT_GLBPAY%'");
	}
	/**
	 * Internal list of configuration keys used for configuration of the module
	 */
	function keys(){
		return array(
         'MODULE_PAYMENT_GLBPAY_STATUS',
         'MODULE_PAYMENT_GLBPAY_MERCHANTID',
         'MODULE_PAYMENT_GLBPAY_SSLKEY',
         'MODULE_PAYMENT_GLBPAY_ORDER_PREFIX',
         'MODULE_PAYMENT_GLBPAY_PROCESSING_STATUS_ID',
         'MODULE_PAYMENT_GLBPAY_ORDER_STATUS_ID',
         'MODULE_PAYMENT_GLBPAY_ZONE',
         'MODULE_PAYMENT_GLBPAY_SORT_ORDER',
         'MODULE_PAYMENT_GLBPAY_HANDLER'
         );
	}
	
	function getIp() { 
		if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {$ip = getenv("HTTP_CLIENT_IP"); }
		else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {$ip = getenv("HTTP_X_FORWARDED_FOR"); }
		else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {$ip = getenv("REMOTE_ADDR"); }
		else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {$ip = $_SERVER['REMOTE_ADDR']; }
		else {$ip = "unknown"; }
		return ($ip); 
	}
	
	function GetWebContent($url,$data){  		
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30); 		
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");     		
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1);  
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); 
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); 
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);		
	    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data))
        );		
		$curl_response = curl_exec($curl); 
		if ($curl_response === false) {
			$info = curl_getinfo($curl);
			curl_close($curl); 
		}
		curl_close($curl);
		return $curl_response; 				                                                              
	}
	
	function replaceCharacter($str){
		$newValue='';
		FOR ($i = 0; $i < strlen($str); $i++) 
		  { 
		    $character= substr($str,$i,1); 
		    if(!(ord($character)>127||ord($character)<0)){
				$newValue.=$character;
		    }
		  } 
		return $newValue;
	}
	
	function strcheck($str='')
	{
		if($str!='')
		{
			if(!strpos($str,':'))
			{
				return $str;
			}
			else
			{
				return substr($str,0,strpos($str,':'));
			}
		}
	}

  }
?>